import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common.utils import ForumDriver


class ForumPost:
    def __init__(self):
        self.driver=ForumDriver.driver
        # 回到首页
        self.driver.find_element(By.CSS_SELECTOR, "#nav_board_index > a").click()
        # 点击“发布帖子”按钮
        self.driver.find_element(By.CSS_SELECTOR,"#bit-forum-content > div.page-header.d-print-none > div > div > div.col-auto.ms-auto.d-print-none > div > a.btn.btn-primary.d-none.d-sm-inline-block.article_post").click()

    def _clear_forum(self):
        # 清除输入框
        self.driver.find_element(By.CSS_SELECTOR, "#article_post_title").clear()

    def PostSucc(self):
        self._clear_forum()
        # 输入标题和内容
        self.driver.find_element(By.CSS_SELECTOR, "#article_post_title").send_keys("Java1")
        self.driver.find_element(By.CSS_SELECTOR,"#edit-article > div.editormd-toolbar > div > ul > li:nth-child(5) > a > i").click()
        time.sleep(1)
        # 滚动到底部
        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
        time.sleep(1)
        # 点击发布
        self.driver.find_element(By.CSS_SELECTOR, "#article_post_submit").click()
        time.sleep(1)
        # 验证发布成功后首页的第一条帖子的标题
        text=self.driver.find_element(By.CSS_SELECTOR,"#artical-items-body > div:nth-child(1) > div > div.col > div.text-truncate").text
        assert text=="Java1"
        # 截图
        ForumDriver.getScreenShot()
        time.sleep(1)


    def PostFail(self):
        # 测试各种发布失败的情况
        test_cases = [
            # (描述, 标题, 内容)
            ("标题和内容都为空", "", ""),
            ("内容为空", "Java2", ""),
            ("标题为空", "", "1"),
            ("标题过长", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "1"),
        ]

        for desc, title, content in test_cases:
            self._clear_forum()
            # 对输入框
            if title:
                self.driver.find_element(By.CSS_SELECTOR, "#article_post_title").send_keys(title)
            if content:
                self.driver.find_element(By.CSS_SELECTOR, "#edit-article > div.editormd-toolbar > div > ul > li:nth-child(5) > a > i").click()
            time.sleep(3)
            # 滚动到底部
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
            time.sleep(1)
            # 点击发布
            self.driver.find_element(By.CSS_SELECTOR, "#article_post_submit").click()

            # 验证：如果发布失败，还是在发布界面
            text = self.driver.find_element(By.XPATH, '//*[@id="bit-forum-content"]/div[1]/div/div/div/h2').text
            assert text == "发新贴"
            # 截图
            ForumDriver.getScreenShot()
            time.sleep(1)






